import json
from datetime import datetime

from OpenSSL.rand import status
from django.forms.models import model_to_dict
from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt

from zuoye20250915.models import device


# Create your views here.
@csrf_exempt
def zuoye0915_device_add(request):
    data=json.loads(request.body)
    if data['name']=='':
        return JsonResponse(
            {
                'msg':'参数必填'
            },status=400
        )
    if device.objects.filter(serial_no=data['serial_no']).exists():
        return JsonResponse(
            {
                'msg','该账号已存在'
            },status=300
        )
    a=device.objects.create(
        serial_no=data['serial_no'],
        name=data['name'],
        type=data['type'],
        location=data['location'],
        status=0,
        last_check=datetime.now()
    )
    return JsonResponse(
        {
            'msg':'添加成功',
            'id':a.id,
            'purchase_data':a.purchase_data
        }
    )
@csrf_exempt
def zuoye0915_device_update(request,id=None):
    if id==None:
        return JsonResponse(
            {
                'msg':'id必填'
            }
        )
    data=json.loads(request.body)
    items=device.objects.get(id=id)
    items.location=data['location']
    items.status=data['status']
    items.purchase_data=datetime.now()
    items.last_check=datetime.now()
    items.save()
    return JsonResponse(
        {
            'item':model_to_dict(items)
        }
    )